/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "test_helpers.h"

#include <iomanip>
#include <iosfwd>
#include <sstream>

namespace OHOS {
namespace SeBaseServices {
namespace UnitTest {
std::string TestHelpers::VectorToHexString(const std::vector<uint8_t> &input)
{
    std::stringstream out;
    std::string hex;

    for (uint8_t value : input) {
        auto curr = static_cast<uint32_t>(value);
        out << std::setw(2) << std::setfill('0') // to hex char width 2
            << std::setiosflags(std::ios::uppercase) << std::hex << curr;
    }
    out >> hex;
    return hex;
}

std::string TestHelpers::VectorToHexString(const uint8_t *input, uint32_t length)
{
    return VectorToHexString({input, input + length});
}

std::vector<uint8_t> TestHelpers::HexStringToVector(const std::string &input)
{
    std::string fix = (input.size() % 2 == 0) ? input : "0" + input; // refix length

    std::vector<uint8_t> out;
    out.reserve(fix.size() / 2); // divide by 2

    for (std::size_t i = 0; i < fix.size(); i += 2) { // next 2 chars
        std::stringstream ss;
        ss << std::hex << fix.substr(i, 2); // next 2 chars
        int32_t ch = 0;
        ss >> ch;
        out.push_back(static_cast<uint8_t>(ch));
    }
    return out;
}

void TestHelpers::VectorFillUp(const std::vector<uint8_t> &input, uint8_t *output, uint32_t *length)
{
    uint32_t index = 0;
    for (auto value : input) {
        if (index >= *length) {
            break;
        }
        output[index++] = value;
    }
    *length = index;
}

void TestHelpers::StringFillUp(const std::string &input, uint8_t *output, uint32_t *length)
{
    VectorFillUp(HexStringToVector(input), output, length);
}

} // namespace UnitTest
} // namespace SeBaseServices
} // namespace OHOS
